using System;
using System.Security.Cryptography;

namespace UserManager
{
    public class RandomCode
    {
        private static RandomCode _ins = new RandomCode("0123456789qwertyuiiopasdfghjklzxcvbnm");
        private char[] _hashChars;
        private Random _rand;

        public RandomCode()
            : this("")
        { }

        public RandomCode(string hashKey)
        {
            this._hashChars = hashKey.ToCharArray();
            this._rand = new Random();
        }

        internal char[] HashChars
        {
            get
            {
                return this._hashChars;
            }
        }

        public string NewCode(int length)
        {
            int cnt = this._hashChars.Length - 1;
            string seed = "";
            char c = char.MinValue;

            while (seed.Length < length)
            {
                int key = this._rand.Next(cnt);
                int vi = this._rand.Next(3);
                if (vi == 0) continue;

                switch (key % vi)
                {
                    case 0:
                        c = this._hashChars[key];
                        break;
                    case 1:
                         c = this._hashChars[cnt - key];
                        break;
                    default:
                        c = this._hashChars[key / vi];
                        break;
                }

                if ((seed.Length > 0) && (seed[seed.Length - 1] == c)) continue;
                seed += c.ToString();
            }

            return seed;
        }

        public static string RamdomString(int length)
        {
            return RandomCode._ins.NewCode(length);
        }

        public static int RandomNumber(int maxValue)
        {
            Random rand = new Random();
            return rand.Next(maxValue);
        }

        public static byte[] RandomBytes(int length)
        {
            byte[] btRand = new byte[length];
            RandomNumberGenerator.Create().GetBytes(btRand);
            return btRand;
        }
    }
}
